﻿namespace Deppton.Model
{
    using System;
    using System.Collections.Generic;
    using System.Globalization;

    public class WithinRangeCondition : Condition
    {
        public override bool Evaluate(Func<string, string> valueResolver, Func<string, NamedList<KeyValuePair<string, string>>> metadataResolver)
        {
            try
            {
                double tolerance = Convert.ToDouble(metadataResolver.Invoke(this.Identifier)["tolerance"], CultureInfo.InvariantCulture);
                double expectedLatitude = Convert.ToDouble(metadataResolver.Invoke(this.Identifier)["latitude"], CultureInfo.InvariantCulture);
                double expectedLongitude = Convert.ToDouble(metadataResolver.Invoke(this.Identifier)["longitude"], CultureInfo.InvariantCulture);

                string[] values = Utilities.UnescapeList(valueResolver.Invoke(this.Identifier));

                if (values.Length != 2)
                {
                    return false;
                }

                double latitude = Convert.ToDouble(values[0], CultureInfo.InvariantCulture);
                double longitude = Convert.ToDouble(values[1], CultureInfo.InvariantCulture);

                return Utilities.IsWithinRange(latitude, longitude, expectedLatitude, expectedLongitude, tolerance);
            }
            catch
            {
                return false;
            }
        }

        public string Identifier
        {
            get;
            set;
        }
    }
}
